
<template>
  <div class="main-container">
    <div class="filtrate-bar">
      <div class="title-box">
        <div class="icon-box">
          <span class="wk wk-my-task icon" />
        </div>
        <span class="text">签约报告</span>
        <j-search-select-tag
          style="width: 150px; margin-left: 15px"
          v-model="personTypeId"
          @change="buTypeChange"
          placeholder="请选择部门"
        >
          <template v-slot>
            <a-select-option v-for="(item, index) in secOptions" :key="index" :value="item.value"
              >{{ item.label }}
            </a-select-option>
          </template>
        </j-search-select-tag>
        <a-range-picker
          :open="rangeVisible"
          style="margin-left: 10px"
          :placeholder="['开始年月', '截止年月']"
          format="YYYY-MM"
          :value="value"
          :mode="mode2"
          @openChange="rangeVisible = !rangeVisible"
          @panelChange="handlePanelChange2"
          @change="handleChange"
        >
          <template slot="renderExtraFooter">
            <a-button size="small" @click="handleRe"> 重置 </a-button>
            <a-button style="margin-left: 15px" type="primary" size="small" @click="handleOk">
              确定
            </a-button></template
          >
        </a-range-picker>
      </div>
    </div>

    <div class="table-content">
      <div class="handle-bar">
        <a-radio-group v-model="typeId" @change="initAxis">
          <a-radio-button value="1">按BU(全业务类型)</a-radio-button>
          <a-radio-button value="2" v-if="userInfo().groupId != '4210'">按仓库(仅仓储)</a-radio-button>
        </a-radio-group>
        <!-- <a-button class="export-btn">导出</a-button> -->
      </div>
      <a-table
        v-if="typeId == '1'"
        :scroll="{ y: 300 }"
        :columns="fieldListBu"
        :data-source="tableList"
        bordered
        :pagination="false"
      >
        <template slot="buId" slot-scope="text, record">
          <a-tooltip placement="top">
            <template slot="title">
              <span>{{ record.name }}</span>
            </template>
            <span v-if="userInfo().groupId == '4210'" class="ellipsis" style="width: 100%">{{ record.name }}</span>
            <span v-else class="ellipsis" style="width: 100%"
              ><a @click="() => showQyTable(record.buId, record.name, record)">{{ record.name }}</a></span
            >
          </a-tooltip>
        </template>
      </a-table>
      <a-table
        v-if="typeId == '2'"
        :scroll="{ y: 300 }"
        :columns="fieldListCang"
        :data-source="tableList"
        bordered
        :pagination="false"
      >
        <template slot="whouseId" slot-scope="text, record">
          <a-tooltip placement="top">
            <template slot="title">
              <span>{{ record.warehouseName }}</span>
            </template>
            <span v-if="userInfo().groupId == '4210'" class="ellipsis" style="width: 100%">{{
              record.warehouseName
            }}</span>
            <span v-else class="ellipsis" style="width: 100%"
              ><a @click="() => showQyTable(record.whouseId, record.warehouseName, record)">{{
                record.warehouseName
              }}</a></span
            >
          </a-tooltip>
        </template>
      </a-table>
    </div>

    <div class="analysis">
      <div style="height: 35px; font-size: 18px; font-weight: 700; text-align: center">{{ zxTitle }}</div>
      <a-row :span="24">
        <a-col :span="24"
          ><div class="analysis-content">
            <div id="analysisAll1" />
          </div>
        </a-col>
      </a-row>
    </div>

    <div class="bottomTable" v-if="userInfo().groupId != '4210' || personTypeId=='nowData'">
      <div style="height: 35px; font-size: 18px; font-weight: 700">{{ qyTitle }}</div>
      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="qyColumns"
        :dataSource="qyDataSource"
        :pagination="false"
        :loading="false"
        :scroll="{ x: 1500, y: 500 }"
        class="j-table-force-nowrap"
      >
        <template slot="customerId_dictText" slot-scope="text, record">
          <a-tooltip placement="top">
            <template slot="title">
              <span>{{ record.customerId_dictText }}</span>
            </template>
            <span class="ellipsis">{{ record.customerId_dictText }}</span>
          </a-tooltip>
        </template>
        <template slot="businessName" slot-scope="text, record">
          <a-tooltip placement="top">
            <template slot="title">
              <span>{{ record.businessName }}</span>
            </template>
            <span class="ellipsis">{{ record.businessName }}</span>
          </a-tooltip>
        </template>
        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px; font-style: italic">无图片</span>
          <img
            v-else
            :src="getImgView(text)"
            height="25px"
            alt=""
            style="max-width: 80px; font-size: 12px; font-style: italic"
          />
        </template>
      </a-table>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { httpAction, getAction } from '@/api/manage'
import JSearchSelectTag from '@/components/dict/JSearchSelectTag'

function number_format(number, decimals, dec_point, thousands_sep) {
  /*
   * 参数说明：
   * number：要格式化的数字
   * decimals：保留几位小数
   * dec_point：小数点符号
   * thousands_sep：千分位符号
   * */
  number = (number + '').replace(/[^0-9+-Ee.]/g, '')
  var n = !isFinite(+number) ? 0 : +number,
    prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
    sep = typeof thousands_sep === 'undefined' ? ',' : thousands_sep,
    dec = typeof dec_point === 'undefined' ? '.' : dec_point,
    s = '',
    toFixedFix = function (n, prec) {
      var k = Math.pow(10, prec)
      return '' + Math.ceil(n * k) / k
    }

  s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.')
  var re = /(-?\d+)(\d{3})/
  while (re.test(s[0])) {
    s[0] = s[0].replace(re, '$1' + sep + '$2')
  }

  if ((s[1] || '').length < prec) {
    s[1] = s[1] || ''
    s[1] += new Array(prec - s[1].length + 1).join('0')
  }
  return s.join(dec)
}
export default {
  /** 客户总量分析 */
  name: 'SummaryReportAll',
  components: {
    JSearchSelectTag,
  },
  data() {
    return {
      rangeVisible: false,
      mode2: ['month', 'month'],
      value: [],
      secOptions: [],
      defaultPersonTypeId: '',
      personTypeId: '',
      personTypeLabel: '',
      defaultPersonTypeLabel: '',
      typeId: '1',

      loading: false,
      fromDate: '',
      thruDate: '',
      chartAnalysis1: null,
      analysis1Option: null,
      url: {
        selectNowUserBySecurityGroupBu2: '/online/api/selectNowUserBySecurityGroupBu2',
        getNewSigningAnalysis: '/online/api/getNewSigningAnalysis',
        getNewSigningAnalysisList: '/online/api/getNewSigningAnalysisList',
        exportXlsUrl: '/online/api/export/exportXlsGraphReport',
      },
      postParams: {}, // 筛选参数
      dataIndex: null,
      list: [],
      axisList: [],
      fieldListBu: [
        {
          title: 'BU',
          align: 'center',
          dataIndex: 'buId',
          key: 'buId',
          width: 150,
          scopedSlots: { customRender: 'buId' },
        },
      ],
      fieldListCang: [
        {
          title: '仓库',
          align: 'center',
          dataIndex: 'whouseId',
          key: 'whouseId',
          width: 150,
          scopedSlots: { customRender: 'whouseId' },
        },
      ],
      tableList: [],

      qyVisible: false,
      qyColumns: [
        // {
        //   title: '#',
        //   dataIndex: '',
        //   key: 'rowIndex',
        //   width: 60,
        //   align: 'center',
        //   customRender: function (t, r, index) {
        //     return parseInt(index) + 1
        //   },
        //   fixed: 'left',
        // },
        {
          title: '客户名称',
          align: 'center',
          dataIndex: 'customerId_dictText',
          width: '150px',
          scopedSlots: { customRender: 'customerId_dictText' },
          sorter: (a, b) => {
            return a.customerId_dictText.localeCompare(b.customerId_dictText)
          },
          ellipsis: true,
        },
        {
          title: '商机名称',
          align: 'center',
          dataIndex: 'businessName',
          width: '150px',
          scopedSlots: { customRender: 'businessName' },
          ellipsis: true,
        },
        {
          title: '商机类型',
          align: 'center',
          dataIndex: 'typeId_dictText',
        },
        {
          title: '客户经理',
          align: 'center',
          dataIndex: 'ownerUserId_dictText',
          sorter: (a, b) => {
            return a.ownerUserId_dictText.localeCompare(b.ownerUserId_dictText)
          },
          ellipsis: true,
        },
        {
          title: '签约金额',
          align: 'center',
          dataIndex: 'estimatedSalesAmount',
          ellipsis: true,
          sorter: (a, b) => a.estimatedSalesAmount - b.estimatedSalesAmount,
          customRender: function (t, r, index) {
            return number_format(t, 0, '.', ',')
          },
        },
        {
          title: '创建时间',
          align: 'center',
          width: 150,
          dataIndex: 'createTime',
          customRender: function (t, r, index) {
            if (t) {
              return t.substr(0, 10)
            }
          },
          ellipsis: true,
        },
        {
          title: '签约时间',
          align: 'center',
          width: 150,
          dataIndex: 'status5Time',
          customRender: function (t, r, index) {
            if (t) {
              return t.substr(0, 10)
            }
          },
          ellipsis: true,
        },
        {
          title: '仓库',
          align: 'center',
          dataIndex: 'warehouseName',
          sorter: (a, b) => {
            return a.warehouseName.localeCompare(b.warehouseName)
          },
          ellipsis: true,
        },
        {
          title: '冷冻销售',
          align: 'center',
          sorter: (a, b) => a.estimatedFreeze - b.estimatedFreeze,
          dataIndex: 'estimatedFreeze',
        },
        {
          title: '冷藏销售',
          align: 'center',
          sorter: (a, b) => a.estimatedRefrigerate - b.estimatedRefrigerate,
          dataIndex: 'estimatedRefrigerate',
        },
        {
          title: '恒温销售',
          align: 'center',
          sorter: (a, b) => a.estimatedConstant - b.estimatedConstant,
          dataIndex: 'estimatedConstant',
        },
        {
          title: '常温销售',
          align: 'center',
          sorter: (a, b) => a.estimatedNormal - b.estimatedNormal,
          dataIndex: 'estimatedNormal',
        },
      ],
      qyDataSource: [],
      qyTitle: '',
      zxTitle: '',
      zxDataList: [],
    }
  },
  computed: {
    // 列表请求参数
    listPostParams() {
      const params = { ...this.postParams }

      if (this.dataIndex !== undefined && this.dataIndex !== null) {
        const dataItem = this.axisList[this.dataIndex]
        delete params.type
        params.startTime = dataItem.type
        params.endTime = dataItem.type
      }

      return params
    },
  },
  created(){
    this.selectSec()
  },
  mounted() {
    
  },
  methods: {
    ...mapGetters(['userInfo']),
    /**
     * 搜索点击
     */
    searchClick(params) {
      this.postParams = params
      this.getDataList()
    },

    /** 图表 */
    initAxis() {
      this.qyVisible = false
      this.chartAnalysis1 = this.echarts.init(document.getElementById('analysisAll1'))

      this.analysis1Option = {
        legend: {
          left: 'right',
          top: '50%',
          data: ['汇总'],
        },
        xAxis: {
          type: 'category',
          data: [],
        },
        yAxis: {
          type: 'value',
        },
        series: [
          {
            name: '汇总',
            data: [],
            type: 'line',
            label: {
              show: true,
              position: 'top',
              formatter: function (params) {
                let res = number_format(params.value, 0, '.', ',')
                return res
              },
            },
          },
        ],
      }
      const param = {}
      param.personTypeId = this.personTypeId
      param.typeId = this.typeId
      param.createTime_fld0_value = this.value[0]
      param.createTime_fld1_value = this.value[1]
      getAction(this.url.getNewSigningAnalysis, param).then((res) => {
        let xAxislist = []
        this.zxDataList = []
        this.fieldListBu = [
          {
            title: 'BU',
            align: 'center',
            dataIndex: 'buId',
            key: 'buId',
            width: 150,
            scopedSlots: { customRender: 'buId' },
          },
        ]
        this.fieldListCang = [
          {
            title: '仓库',
            align: 'center',
            dataIndex: 'whouseId',
            key: 'whouseId',
            width: 150,
            scopedSlots: { customRender: 'whouseId' },
          },
        ]
        res.result.workMap.chartList.forEach((e) => {
          if (this.typeId == '1') {
            this.fieldListBu.push({
              title: e.key,
              align: 'center',
              dataIndex: e.key,
              key: e.key,
              customRender: function (t, r, index) {
                return number_format(t, 0, '.', ',')
              },
            })
          }
          if (this.typeId == '2') {
            this.fieldListCang.push({
              title: e.key,
              align: 'center',
              dataIndex: e.key,
              key: e.key,
              customRender: function (t, r, index) {
                return number_format(t, 0, '.', ',')
              },
            })
          }
          xAxislist.push(e.key)
          this.zxDataList.push(e.value)
        })
        this.zxTitle =
          this.value[0] +
          '至' +
          this.value[1] +
          '月' +
          this.personTypeLabel +
          (this.typeId == '1' ? '成功签约金额' : '成功签约金额')
        this.analysis1Option.xAxis.data = xAxislist
        this.analysis1Option.series[0].data = this.zxDataList

        this.$nextTick(() => {
          this.tableList = res.result.workMap.buChartList
          this.chartAnalysis1.setOption(this.analysis1Option, true)
          this.showQyTable('ALL')
        })
      })
    },

    handleChange(value) {
      if (value.length == 0) {
        this.value = this.createDateDate()
        this.initAxis()
      } else {
        let dateA = value[0].format('YYYY-MM')
        let dateB = value[1].format('YYYY-MM')
        this.value = [dateA, dateB]
      }
    },
    handlePanelChange2(value, mode) {
      let dateA = value[0].format('YYYY-MM')
      let dateB = value[1].format('YYYY-MM')
      this.value = [dateA, dateB]
      this.mode2 = [mode[0] === 'date' ? 'month' : mode[0], mode[1] === 'date' ? 'month' : mode[1]]
    },
    selectSec() {
      this.value = this.createDateDate()
      const param = {}
      getAction(this.url.selectNowUserBySecurityGroupBu2, param).then((res) => {
        if (res.success) {
          this.secOptions = res.result.list || []
          if (res.result.list) {
            this.personTypeId = res.result.list[0].value
            this.defaultPersonTypeId = res.result.list[0].value
            this.personTypeLabel = res.result.list[0].label
            this.defaultPersonTypeLabel = res.result.list[0].label
          }
          this.$nextTick(() => {
            this.initAxis()
          })
        }
      })
    },
    buTypeChange(e) {
      if (e === undefined) {
        this.personTypeId = this.defaultPersonTypeId
        this.personTypeLabel = this.defaultPersonTypeLabel
      } else {
        this.secOptions.forEach((item) => {
          if (item.value == e) {
            this.personTypeLabel = item.label
          }
        })
      }
      this.$nextTick(() => {
        this.initAxis()
      })
    },
    handleRe() {
      this.value = this.createDateDate()
    },
    handleOk() {
      this.rangeVisible = false
      this.initAxis()
    },
    showQyTable(id, name, record) {
      if (id == '_NA_') {
        name = '汇总'
      }
      if (id == 'ALL') {
        name = '详细'
      }
      this.qyVisible = true
      this.qyTitle =
        this.personTypeLabel + this.value[0] + '至' + this.value[1] + '月' + (name ? name : '') + '签约列表'
      let theId = ''
      if (id == 'ALL') {
        this.analysis1Option.series[0].data = this.zxDataList
        if (this.typeId == '1') {
          this.tableList.forEach((e, index) => {
            if (index != this.tableList.length - 1) {
              theId = theId + e.buId + ','
            }
          })
        }
        if (this.typeId == '2') {
          this.tableList.forEach((e, index) => {
            if (index != this.tableList.length - 1) {
              theId = theId + e.whouseId + ','
            }
          })
        }
      } else if (id == '_NA_') {
        this.zxTitle =
          this.value[0] +
          '至' +
          this.value[1] +
          '月' +
          this.personTypeLabel +
          (this.typeId == '1' ? '成功签约金额' : '成功签约金额')
        let itemlist = []
        for (let y in this.analysis1Option.xAxis.data) {
          for (let i in record) {
            if (this.analysis1Option.xAxis.data[y] == i) {
              itemlist.push(record[i])
            }
          }
        }
        this.analysis1Option.series[0].data = itemlist
        if (this.typeId == '1') {
          this.tableList.forEach((e, index) => {
            if (index != this.tableList.length - 1) {
              theId = theId + e.buId + ','
            }
          })
        }
        if (this.typeId == '2') {
          this.tableList.forEach((e, index) => {
            if (index != this.tableList.length - 1) {
              theId = theId + e.whouseId + ','
            }
          })
        }
      } else {
        theId = id
        this.zxTitle =
          this.value[0] + '至' + this.value[1] + '月' + name + (this.typeId == '1' ? '成功签约金额' : '成功签约金额')
        let itemlist = []
        for (let y in this.analysis1Option.xAxis.data) {
          for (let i in record) {
            if (this.analysis1Option.xAxis.data[y] == i) {
              itemlist.push(record[i])
            }
          }
        }
        this.analysis1Option.series[0].data = itemlist
      }
      const param1 = {}
      param1.buId = this.personTypeId
      param1.personTypeId = theId
      param1.typeId = this.typeId
      param1.createTime_fld0_value = this.value[0]
      param1.createTime_fld1_value = this.value[1]
      getAction(this.url.getNewSigningAnalysisList, param1).then((res) => {
        if (res.success) {
          this.qyDataSource = res.result.workMap.successCrmBusinessTotalAmountList
        }
      })
      this.$nextTick(() => {
        this.chartAnalysis1.setOption(this.analysis1Option, true)
      })
    },

    /**
     * 导出点击
     */
    exportClick() {
      this.requestExportInfo(biCustomerTotalListExportAPI, this.listPostParams)
    },

    createDateDate() {
      let datelist = []
      let date = new Date()
      let Y = date.getFullYear()
      let M = date.getMonth() + 1
      let lastY
      let lastM
      if (M > 6) {
        lastY = Y
        lastM = M - 6
      } else {
        lastY = Y - 1
        lastM = M + 6
      }
      if (M < 10) {
        M = '0' + M
      }
      if (lastM < 10) {
        lastM = '0' + lastM
      }
      let monthA = Y + '-' + M
      let monthB = lastY + '-' + lastM

      return [monthB, monthA]
    },
  },
}
</script>


<style lang="less" scoped>
/deep/ .ant-table-thead > tr > th,
.ant-table-tbody > tr > td {
  padding: 10px 4px;
}
.main-container {
  border: 1px solid #e6e6e6;
  border-radius: 2px;
  background-color: white;
  height: 100%;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  position: relative;
}

.filtrate-bar {
  background-color: white;
  padding: 15px 20px 5px 20px;
  margin-right: 15px;
  line-height: 34px;
  .icon-box {
    width: 34px;
    height: 34px;
    text-align: center;
    line-height: 34px;
    color: #168a40;
    background-color: #dfe8ff;
    border-radius: 50%;
    margin-right: 10px;
    float: left;
  }
  .text {
    font-size: 17px;
    font-weight: 700;
  }
}

.content-title {
  padding: 10px 20px 5px;
  font-size: 16px;
  color: #333;
}
.analysis {
  margin-top: 10px;
  .analysis-content {
    padding: 8px 10px;
    .tips {
      padding-left: 8%;
      font-size: 12px;
      div {
        margin-bottom: 8px;
      }
    }
    #analysisAll1 {
      margin: 0 auto;
      width: 95%;
      height: 400px;
    }
    #analysisAll2 {
      margin: 0 auto;
      width: 95%;
      height: 400px;
    }
    #analysisAll3 {
      margin: 0 auto;
      width: 95%;
      height: 400px;
    }
  }
}

.axis-content {
  padding: 20px 10% 40px;
  position: relative;
  .axismain,
  #summaryAll1 {
    margin: 0 auto;
    width: 100%;
    height: 400px;
  }
}
.bottomTable {
  padding: 30px;
}

.table-content {
  padding: 0 30px 20px 30px;
}

.export-button {
  float: right;
  margin-right: 22px;
}

// 导出操作bug
.handle-bar {
  margin-bottom: 8px;
}

.search-box {
  padding-right: 15px;
}

.radio-box {
  padding: 0 20px;
  margin-bottom: 15px;
  /deep/ .el-radio__label {
    color: #99a9bf !important;
  }
}

.static {
  padding: 0 20px;
  margin-bottom: 10px;
  .text {
    font-size: 13px;
    color: #99a9bf;
    display: inline-block;
  }
  .text:not(:last-child) {
    margin-right: 15px;
  }
}
/deep/ .ant-table-wrapper {
  border: 1px solid #ebeef5;
}
/deep/ .ant-table-placeholder {
  display: none;
}
</style>

